/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package downloadmanager.downloader;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Administrator
 */
public class SegmentCalculator {

    public final int MIN_SEGMENT_SIZE = 200000;

    public CalculatedSegment[] getSegments(int segmentCount, RemoteFileInfo remoteFileInfo) {
        long minSize = MIN_SEGMENT_SIZE;
        long segmentSize = remoteFileInfo.getFileSize() / (long) segmentCount;

        while (segmentCount > 1 && segmentSize < minSize) {
            segmentCount--;
            segmentSize = remoteFileInfo.getFileSize() / (long) segmentCount;
        }

        long startPosition = 0;

        List<CalculatedSegment> segments = new ArrayList<CalculatedSegment>();

        for (int i = 0; i < segmentCount; i++) {
            if (segmentCount - 1 == i) {
                segments.add(new CalculatedSegment(startPosition, remoteFileInfo.getFileSize()));
            } else {
                segments.add(new CalculatedSegment(startPosition, startPosition + (int) segmentSize));
            }

            startPosition = segments.get(segments.size() - 1).getEndPosition();
        }

        return segments.toArray(new CalculatedSegment[segments.size()]);
    }
}
